/**
 * 自定义指令
 */

/**
 * 防抖指令
 * v-debounce="{ handler: handleClick, delay: 300 }"
 */
const debounce = {
  mounted(el, binding) {
    let timer = null
    const { handler, delay = 300 } = binding.value
    
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        handler()
      }, delay)
    })
  }
}

/**
 * 节流指令
 * v-throttle="{ handler: handleClick, delay: 300 }"
 */
const throttle = {
  mounted(el, binding) {
    let timer = null
    const { handler, delay = 300 } = binding.value
    
    el.addEventListener('click', () => {
      if (!timer) {
        timer = setTimeout(() => {
          handler()
          timer = null
        }, delay)
      }
    })
  }
}

/**
 * 权限指令
 * v-permission="'admin'"
 * v-permission="['admin', 'user']"
 */
const permission = {
  mounted(el, binding) {
    const { value } = binding
    const userRole = localStorage.getItem('userRole')
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    
    if (!value) return
    
    let hasPermission = false
    
    if (typeof value === 'string') {
      hasPermission = userRole === value || userPermissions.includes(value)
    } else if (Array.isArray(value)) {
      hasPermission = value.some(permission => 
        userRole === permission || userPermissions.includes(permission)
      )
    }
    
    if (!hasPermission) {
      if (el) el.style.display = 'none'
    }
  },
  updated(el, binding) {
    permission.mounted(el, binding)
  }
}

/**
 * 自动聚焦指令
 * v-focus
 */
const focus = {
  mounted(el) {
    if (el) el.focus()
  }
}

/**
 * 点击外部指令
 * v-click-outside="handleClickOutside"
 */
const clickOutside = {
  mounted(el, binding) {
    el.clickOutsideEvent = function(event) {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el.clickOutsideEvent)
  },
  unmounted(el) {
    document.removeEventListener('click', el.clickOutsideEvent)
  }
}

/**
 * 复制到剪贴板指令
 * v-copy="'复制的内容'"
 */
const copy = {
  mounted(el, binding) {
    el.addEventListener('click', () => {
      const text = binding.value
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          console.log('复制成功')
          // 可以添加成功提示
        }).catch(err => {
          console.error('复制失败:', err)
        })
      } else {
        // 兼容旧浏览器
        const textArea = document.createElement('textarea')
        textArea.value = text
        if (textArea) {
          textArea.style.position = 'fixed'
          textArea.style.opacity = '0'
        }
        document.body.appendChild(textArea)
        if (textArea) textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        console.log('复制成功')
      }
    })
  }
}

/**
 * 拖拽指令
 * v-draggable
 */
const draggable = {
  mounted(el) {
    if (el) {
      el.style.cursor = 'move'
      el.style.position = 'absolute'
    }
    
    let isDragging = false
    let currentX
    let currentY
    let initialX
    let initialY
    let xOffset = 0
    let yOffset = 0
    
    el.addEventListener('mousedown', dragStart)
    document.addEventListener('mousemove', drag)
    document.addEventListener('mouseup', dragEnd)
    
    function dragStart(e) {
      initialX = e.clientX - xOffset
      initialY = e.clientY - yOffset
      
      if (e.target === el) {
        isDragging = true
      }
    }
    
    function drag(e) {
      if (isDragging) {
        e.preventDefault()
        currentX = e.clientX - initialX
        currentY = e.clientY - initialY
        xOffset = currentX
        yOffset = currentY
        
        if (el) el.style.transform = `translate3d(${currentX}px, ${currentY}px, 0)`
      }
    }
    
    function dragEnd() {
      initialX = currentX
      initialY = currentY
      isDragging = false
    }
  }
}

/**
 * 懒加载指令
 * v-lazy="imageUrl"
 */
const lazy = {
  mounted(el, binding) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target
          img.src = binding.value
          if (img) img.style.opacity = '0'
          if (img) img.style.transition = 'opacity 0.3s'
          
          img.onload = () => {
            if (img) img.style.opacity = '1'
          }
          
          observer.unobserve(img)
        }
      })
    }, {
      threshold: 0.1
    })
    
    observer.observe(el)
  }
}

/**
 * 长按指令
 * v-long-press="handleLongPress"
 */
const longPress = {
  mounted(el, binding) {
    let timer = null
    const { value: handler, arg = 500 } = binding
    
    el.addEventListener('mousedown', () => {
      timer = setTimeout(() => {
        handler()
      }, parseInt(arg))
    })
    
    el.addEventListener('mouseup', () => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    })
    
    el.addEventListener('mouseleave', () => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    })
  }
}

/**
 * 加载状态指令
 * v-loading="isLoading"
 */
const loading = {
  mounted(el, binding) {
    updateLoading(el, binding)
  },
  updated(el, binding) {
    updateLoading(el, binding)
  }
}

function updateLoading(el, binding) {
  if (binding.value) {
    if (el) el.style.position = 'relative'
    
    const loadingEl = document.createElement('div')
    loadingEl.className = 'v-loading-overlay'
    loadingEl.innerHTML = `
      <div class="v-loading-spinner">
        <div class="v-loading-dot"></div>
        <div class="v-loading-dot"></div>
        <div class="v-loading-dot"></div>
      </div>
    `
    
    // 添加样式
    const style = document.createElement('style')
    style.textContent = `
      .v-loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
      }
      .v-loading-spinner {
        display: flex;
        gap: 4px;
      }
      .v-loading-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #2563eb;
        animation: v-loading-bounce 1.4s ease-in-out infinite both;
      }
      .v-loading-dot:nth-child(1) { animation-delay: -0.32s; }
      .v-loading-dot:nth-child(2) { animation-delay: -0.16s; }
      @keyframes v-loading-bounce {
        0%, 80%, 100% { transform: scale(0); }
        40% { transform: scale(1); }
      }
    `
    
    if (!document.querySelector('#v-loading-style')) {
      style.id = 'v-loading-style'
      document.head.appendChild(style)
    }
    
    if (el) el.appendChild(loadingEl)
  } else {
    const loadingEl = el && el.querySelector('.v-loading-overlay')
    if (loadingEl) {
      loadingEl.remove()
    }
  }
}

/**
 * 无限滚动指令
 * v-infinite-scroll="loadMore"
 */
const infiniteScroll = {
  mounted(el, binding) {
    const handler = binding.value
    const threshold = binding.arg || 100
    
    el.addEventListener('scroll', () => {
      const { scrollTop, scrollHeight, clientHeight } = el
      
      if (scrollTop + clientHeight >= scrollHeight - threshold) {
        handler()
      }
    })
  }
}

/**
 * 设置指令
 */
export function setupDirectives(app) {
  app.directive('debounce', debounce)
  app.directive('throttle', throttle)
  app.directive('permission', permission)
  app.directive('focus', focus)
  app.directive('click-outside', clickOutside)
  app.directive('copy', copy)
  app.directive('draggable', draggable)
  app.directive('lazy', lazy)
  app.directive('long-press', longPress)
  app.directive('loading', loading)
  app.directive('infinite-scroll', infiniteScroll)
}

export default {
  debounce,
  throttle,
  permission,
  focus,
  clickOutside,
  copy,
  draggable,
  lazy,
  longPress,
  loading,
  infiniteScroll,
  setupDirectives
} 